import { Connection } from "mysql";
import path from "path";
import {
  createDBConnection,
  Logger,
  ReplicationEnum,
  RpcConnection,
  SceneIdEnum,
  ServerEnum,
  ServerPort,
} from "../common";
import { forkSync } from "./../scene/utils";
import { Singleton } from "../common/common/base";

export class ReplicationManager extends Singleton {
  static get Instance() {
    return super.GetInstance<ReplicationManager>();
  }

  connection: Connection;
  game: RpcConnection;
  logger = new Logger("ReplicationManager");

  nextReplicationId = SceneIdEnum.Replication;

  async init() {
    await new Promise((rs) => setTimeout(rs, 1000));
    this.connection = await createDBConnection();

    this.game = await RpcConnection.Create({
      netOptions: {
        port: ServerPort.Game,
        host: "localhost",
      },
      implement: this,
      logger: this.logger,
    });

    const { error } = await this.game.call({
      name: "registerServer",
      params: [ServerEnum.Replication],
    });

    if (error) {
      this.logger.fatal(error);
      return;
    }

    this.logger.info(`ReplicationManager服务启动！`);
  }

  async createReplication(replicationType: ReplicationEnum) {
    if (this.nextReplicationId >= 2 ** 30) {
      this.nextReplicationId = SceneIdEnum.Replication;
    }
    const id = this.nextReplicationId++;
    switch (replicationType) {
      case ReplicationEnum.Replication1:
        await forkSync(path.resolve(__dirname, "./replication/Replication1"), [String(id)]);
        break;
      default:
        break;
    }
    return id;
  }
}
